package com.shiningstars.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.os.Looper;
import android.support.v4.app.NotificationCompat;

import com.shiningstars.R;
import com.shiningstars.general.Config;
import com.shiningstars.general.Constants;
import com.shiningstars.general.Messages;
import com.shiningstars.general.Utilities;
import com.shiningstars.php.WebHelper;
import com.shiningstars.tools.ExceptionHandler;

public class UpdateService extends Service implements Constants, Config, Messages {

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {

		Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this));

		final WebHelper webHelper = new WebHelper();

		new Thread() {
			@Override
			public void run() {

				Looper.prepare();

				try {
					JSONObject json = webHelper.getLatestVersionDetails(getApplicationContext());

					if (null != json && json.getBoolean(SUCCESS)) {
						PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);

						String appVersion = packageInfo.versionName;
						String latestVersion = json.getString(LATEST_APP_VERSION);

						String directory = Environment.getExternalStorageDirectory().getPath() + MY_SSP;
						File dir = new File(directory);
						File file = new File(directory, SSP_APK);

						if (appVersion.equals(latestVersion)) {
							Utilities.removeSharedPreference(getApplicationContext(), LATEST_APP_VERSION);
							file.delete();
							dir.delete();
						} else {
							String fileDownloadStatus = Utilities.getSharedPreference(getApplicationContext(),
									LATEST_APP_VERSION);
							if (!DOWNLOADED.equals(fileDownloadStatus)) {
								file.delete();
								dir.delete();
								dir.mkdir();

								String downloadFilePath = json.getString(FILE_PATH).replace(BACKSLASH, BLANK);

								Utilities.setSharedPreference(getApplicationContext(), LATEST_APP_VERSION, STARTED);
								downloadFile(file, downloadFilePath);
								Utilities.setSharedPreference(getApplicationContext(), LATEST_APP_VERSION, DOWNLOADED);

								fileDownloadStatus = DOWNLOADED;
							}

							if (DOWNLOADED.equals(fileDownloadStatus)) {
								if (file.exists()) {
									Intent intent = new Intent(Intent.ACTION_VIEW);
									intent.setDataAndType(Uri.fromFile(file), INSTALL_TYPE);

									PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
											intent, 0);
									Uri notificationSound = RingtoneManager
											.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

									long pattern[] = { 0, 100, 200, 300, 400 };

									NotificationCompat.Builder builder = new NotificationCompat.Builder(
											getApplicationContext()).setContentTitle(SSP)
											.setSmallIcon(R.drawable.ic_launcher).setContentIntent(pendingIntent)
											.setAutoCancel(true).setSound(notificationSound).setVibrate(pattern);

									builder.setContentText(SSP_UPDATE);
									NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
									notificationManager.notify(0, builder.build());
								} else {
									Utilities.removeSharedPreference(getApplicationContext(), LATEST_APP_VERSION);
									file.delete();
									dir.delete();
								}
							}
						}
					}
				} catch (IllegalStateException e) {
					Utilities.logError(getApplicationContext(), UpdateService.class.getName(), e);
				} catch (JSONException e) {
					Utilities.logError(getApplicationContext(), UpdateService.class.getName(), e);
				} catch (NameNotFoundException e) {
					Utilities.logError(getApplicationContext(), UpdateService.class.getName(), e);
				} catch (IOException e) {
				}

				stopService(new Intent(getApplicationContext(), UpdateService.class));

				Looper.loop();
				Looper.myLooper().quit();
			}
		}.start();

		return START_NOT_STICKY;
	}

	private void downloadFile(File file, String downloadFilePath) throws IOException {

		URL url = new URL(downloadFilePath);

		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		urlConnection.setRequestMethod(GET);
		urlConnection.setDoOutput(true);
		urlConnection.connect();

		InputStream inputStream = urlConnection.getInputStream();

		byte[] buffer = new byte[1024];
		int bufferLength = 0;

		FileOutputStream fileOutput = new FileOutputStream(file);

		while ((bufferLength = inputStream.read(buffer)) > 0) {
			fileOutput.write(buffer, 0, bufferLength);
		}

		fileOutput.close();
	}
}